package com.xin.di.uav.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.xin.di.uav.common.response.TreeResp;

import java.util.List;
import java.util.stream.Collectors;

public class TreeNodeTree {
    public static List<TreeResp> buildTree(List<TreeResp> list) {
        // 获取所有根节点（pid为空的节点）
        return list.stream().filter(node -> ObjectUtils.isEmpty(node.getParentId())).peek(root -> root.setChildren(getChildren(root, list))).collect(Collectors.toList());
    }

    private static List<TreeResp> getChildren(TreeResp parent, List<TreeResp> list) {
        List<TreeResp> children = list.stream().filter(node -> parent.getId().equals(node.getParentId())).peek(child -> child.setChildren(getChildren(child, list))).collect(Collectors.toList());
        return children.isEmpty() ? null : children;
    }
}
